<?php
/**
 * User
 *
 * PHP version 5
 *
 * @category Model
 * @package  MIAOCMS
 * @version  1.0
 * @author   Arlon <MIAOCMS@google.com>

 * @link     http://www.MIAOCMS.net
 */
class User extends AppModel {

    var $name = 'User';    
	
    /*var $actsAs = array(
    		'Acl' => array('type' => 'requester'),
    );*/
    
    var $hasAndBelongsToMany = array(
    		'Role' => array(
    				'className'              => 'Role',
    				'joinTable'              => 'user_roles',
    				'foreignKey'             => 'user_id', // 对应本模块的id
    				'associationForeignKey'  => 'role_id', // 对应tag的id
    				// 'conditions'             => array('UserRole.started >' => ''),
    				'unique'                 => 'keepExisting',
    		// 'limit'        => 100,
    		'dependent'            => false,
    		'exclusive'            => false,
    		'fields' => array('id','name','alias','price'),
    		'order' => 'Role.updated desc',
        ),
        'Company' => array(
            'className'              => 'Company',
            'joinTable'              => 'company_members',
            'foreignKey'             => 'user_id', // 对应本模块的id
            'associationForeignKey'  => 'company_id', // 对应tag的id
            'unique'                 => 'keepExisting',
            'dependent'            => false,
            'exclusive'            => false,
            'fields' => array('id','name','groupid'),
            'order' => 'Company.id desc',
        ),
    );
    
    var $hasOne = array(
        'UserSetting' => array(
			'className'     => 'UserSetting',
			'foreignKey'    => 'id',
			'dependent'=> false
        ),
    
    );
    var $hasMany = array(
        'Oauthbind' => array(
			'className'     => 'Oauthbind',
			'foreignKey'    => 'user_id',
			'dependent'=> false,
            'fields' => array('id','user_id','source','oauth_openid','oauth_token','oauth_name','expires','refresh_token'),
        )
    );
    
//     var $belongsTo = array('Role');

//    var $validate = array(
//        'mobile' => array(
//    		'notempty'=>array(
//	            'rule' => 'notEmpty',
//	            'message' => 'This field cannot be left blank.',
//    		),
//        )
//    );

    public function afterSave($created=false){
        if( $this->id && $created ){
            if( Configure::read('Easemob.open') == 1) {
                App::uses('EasemobUtility','Utility');
                if(empty( $this->data['User']['username'] )){
                    $this->data['User']['username'] = $this->data['User']['mobile'];
                    if(empty( $this->data['User']['username'] )) {
                        $this->data['User']['username'] = $this->data['User']['email'];
                    }
                    if(empty( $this->data['User']['username'] )) {
                        $this->data['User']['username'] = $this->id;
                    }
                }
                EasemobUtility::register($this->id, $this->data['User']['invite_code'], $this->data['User']['username']);
            }
        }
    }
    
    public function beforeDelete($cascade = ture) {
        Cakelog::debug("skip User delete.\n url:".Router::url()."\n session:".var_export(CakeSession::read('Auth.User'),true)."\n user_roles id:".$this->id);
        return false;
    }

    // used in Cake\Model\Behavior\AclBehavior.php(108)
    function parentNode(){
    	if (!$this->id && empty($this->data)) {
    		return null;
    	}
    	$data = $this->data;
    	if (empty($this->data)) {
    		$data = $this->read(); // 读取role_id字段值
    	}
    	if (!isset($data['Role']) || empty($data['Role'])) {
    		$role_ids = explode(',',$data['User']['role_id']);
    		$roles = array_filter($role_ids);
    		return array('Role' => array('id' => $roles));
    	} else {
    		$roles = array();
    		foreach($data['Role'] as $role){
    			$roles[] = $role['role_id'];
    		}
    		return array('Role' => array('id' => $roles));
    	}
    }

	function userlist($page,$count) {
		$this->recursive = -1;
        $userlist = $this->find('all',array(
        	'conditions'=>array('sina_uid >0','status'=>1,'deleted'=>0 ),
        	'page'=>$page,
        	'limit'=>$count,
        	'order'=>'id desc'
        ));
        return $userlist;
    }
    
    public function getUserWxes( $limit = 1 ){
    	$wx = loadModelObject('Wx');
    	$user_wxes = $wx->find('all',array(
    			'conditions'=> 	array('Wx.creator' => $this->currentUser['id']),
    			'joins' => array(array(
    					'table' => 'oauthbinds',
    					'alias' => 'Oauthbind',
    					'type' => 'inner',
    					'conditions' => array(
    							'Wx.creator=Oauthbind.user_id',
    							'Wx.oauth_appid=Oauthbind.oauth_openid',
    							'Oauthbind.source'=>'wechatComp',
    							//'Oauthbind.updated >' => time() - 7200,
    					)
    			)),
    			'order' => 'Oauthbind.updated desc',
    			'fields' => 'Wx.*,Oauthbind.*',
    			'limit' => $limit,
    	));
    	if( $limit == 1 && !empty($user_wxes)) {
    		return $user_wxes[0];
    	}
    	return $user_wxes;
    }
    
    public function getUserByMobile($mobile) {
        $data = $this->find('first', array(
            'conditions' => array('User.mobile' => $mobile),
            'recursive' => 1,
        ));
        if(empty($data['User'])) {
            return array();
        }
    
        if( !is_array($data['User']['role_id']) ) {
            $data['User']['role_id'] = array_filter(explode(',',$data['User']['role_id']));
        }
    
        if( !empty($data['Role']) ) {
            foreach($data['Role'] as $k=>$role) {
                $data['Role'][$k]['started'] = $role['UserRole']['started'];
                $data['Role'][$k]['ended'] = $role['UserRole']['ended'];
                unset($data['Role'][$k]['UserRole']);
                if( !in_array($role['id'],$data['User']['role_id']) ){
                    $data['User']['role_id'][] = $role['id'];
                }
            }
        }
        if( !empty($data['Company']) ) {
            foreach($data['Company'] as $k => $com) {
                $data['Company'][$k]['role_id'] = $com['CompanyMember']['role_id'];
                unset($data['Company'][$k]['CompanyMember']);
            }
        }
    
        if( ! in_array(2,$data['User']['role_id']) ) {
            $data['User']['role_id'][] = 2;
        }
        $data['User']['role_id'] = array_unique($data['User']['role_id']);
        if( !empty($data['UserSetting']) ) {
            $data['UserSetting'] = json_decode($data['UserSetting']['settings'],true);
        }
        $data['User']['Role'] =  $data['Role'];
        $data['User']['Oauthbind'] = $data['Oauthbind'];
        //unset($data['Role']);unset($data['Oauthbind']);
        return $data;
    }
    
    
    public function getUserByEmail($email) {
    	$data = $this->find('first', array(
    			'conditions' => array('User.email' => $email),
    			'recursive' => 1,
    	));
    	if(empty($data['User'])) {
    		return array();
    	}
    
    	if( !is_array($data['User']['role_id']) ) {
    		$data['User']['role_id'] = array_filter(explode(',',$data['User']['role_id']));
    	}
    
    
    	 
    	if( !empty($data['Role']) ) {
    		foreach($data['Role'] as $role) {
    			if( !in_array($role['id'],$data['User']['role_id']) ){
    				$data['User']['role_id'][] = $role['id'];
    			}
    		}
    	}
    	if( ! in_array(2,$data['User']['role_id']) ) {
    		$data['User']['role_id'][] = 2;
    	}
    	$data['User']['role_id'] = array_unique($data['User']['role_id']);
    	if( !empty($data['UserSetting']) ) {
    		$data['UserSetting'] = json_decode($data['UserSetting']['settings'],true);
    	}
    
    	return $data;
    }
    
    public function getUserInfo($user_id){
    
    	if( !empty($this->userinfo) && $this->userinfo['User']['id'] == $user_id ) {
    		return $this->userinfo;
    	}
    
    	$data = $this->find('first', array(
    			'conditions' => array('User.id' => $user_id),
    			'recursive' => 1,
    	));
    	if( empty($data['User']) ) {
    		return array();
    	}
    	if( !is_array($data['User']['role_id']) ) {
    		$data['User']['role_id'] = array_filter(explode(',',$data['User']['role_id']));
    	}
    	 
    	if( !empty($data['Role']) ) {
    		foreach($data['Role'] as $role) {
    			if( !in_array($role['id'],$data['User']['role_id']) ){
    				$data['User']['role_id'][] = $role['id'];
    			}
    		}
    	}
    	$data['User']['role_id'] = array_unique($data['User']['role_id']);
    	if( !empty($data['UserSetting']) ) {
    		$data['UserSetting'] = json_decode($data['UserSetting']['settings'],true);
    	}
    
    	if( ! in_array(2,$data['User']['role_id']) ) {
    		$data['User']['role_id'][] = 2;
    	}
    
    	$data['User']['Role'] =  $data['Role'];
    	$data['User']['Oauthbind'] =  $data['Oauthbind'];
    	$this->userinfo =  $data;
    	return $data;
    }
    
    public function isPaidUser($user_id) {
    	if( empty($this->userinfo) || $this->userinfo['User']['id'] != $user_id ) {
    		$this->userinfo = $this->getUserInfo($user_id);
    	}
    
    	if( count($this->userinfo['User']['role_id']) > 1 ) { //付费会员用户组数大于1
    		return true;
    	}
    	else{
    		return false;
    	}
    }
    
    public function getOauthOpenId($uid,$source) {
    	$oauth = loadModelObject('Oauthbind');
    	$result = $oauth->find('first',array(
    			'conditions' => array( 'user_id'=>$uid,'source'=> $source ),
    			'recursive' => -1,
    	));
    	if( !empty($result) ) {
    		return $result['Oauthbind']['oauth_openid'];
    	}
    	return null;
    }
    
    public function __construct($id=false,$table=null,$ds=null) {
    	parent::__construct($id,$table,$ds);
    	/* 设置用户权限的开始结束时间条件，获取有效的用户权限，过期的都去除  */
    	$this->hasAndBelongsToMany['Role']['conditions'] = array(
    			'UserRole.started <' => date('Y-m-d H:i:s'),
    			'UserRole.ended >' => date('Y-m-d H:i:s'),
    	);
    	 
    }
    
    public function getUserScore($user_id) {
    	$data = $this->find('first',array(
    			'conditions'=>array( 'id' => $user_id,),
    			'fields' => 'score',
    			'recursive' => -1,
    	));
    	return $data['User']['score'];
    }
    
    
    function getNewUCUserId($username,$passwd,$email,$ip) {
    	if(defined('UC_APPID')){
    		App::import('Vendor', '',array('file' => 'uc_client'.DS.'client.php'));
    		if(UC_DBCHARSET =='gbk'){
    			App::uses('Charset', 'Lib');
    			$username = Charset::utf8_gbk($username);
    		}
    
    		$i = 0;
    		do{
    			$uid = uc_user_register($username,$passwd,$email,'','', $ip);
    			if($uid<=0){
    				if($uid == -1) {
    					$error_msg = '用户名不合法';
    				} elseif($uid == -2) {
    					$error_msg = '包含不允许注册的词语';
    				} elseif($uid == -3) {
    					$error_msg = '用户名已经存在';
    				} elseif($uid == -4) {
    					$error_msg = 'Email 格式有误';
    				} elseif($uid == -5) {
    					$error_msg = 'Email 不允许注册';
    				} elseif($uid == -6) {
    					$error_msg = '该 Email 已经被注册';
    				} else{
    					$error_msg = '未知错误';
    				}
    			}
    			else{
    				return $uid;
    			}
    			$i++;
    		}while($uid < 0 && $i < 5);
    		echo $error_msg;exit;
    	}
    	return null;
    }
}
?>